import os
import uuid
from datetime import datetime
import aiofiles
from fastapi import UploadFile, HTTPException
from ..config import settings
import logging

logger = logging.getLogger(__name__)


class FileService:
    @staticmethod
    async def save_upload_file(file: UploadFile) -> dict:
        """
        保存上传的文件并返回相关信息

        参数:
            file: FastAPI的UploadFile对象
        返回:
            包含保存文件信息的字典
        """
        try:
            # 验证文件类型
            if not file.content_type.startswith('image/'):
                raise HTTPException(status_code=400, detail="只接受图片文件")

            # 生成保存路径
            file_extension = os.path.splitext(file.filename)[1]
            unique_filename = f"{uuid.uuid4()}{file_extension}"
            date_path = datetime.now().strftime("%Y/%m/%d")
            save_dir = os.path.join(settings.UPLOAD_DIR, date_path)
            os.makedirs(save_dir, exist_ok=True)

            file_path = os.path.join(save_dir, unique_filename)

            # 保存文件
            async with aiofiles.open(file_path, 'wb') as out_file:
                while content := await file.read(1024 * 1024):
                    await out_file.write(content)

            relative_path = os.path.join(date_path, unique_filename)
            return {
                "status": "success",
                "message": "文件上传成功",
                "filename": file.filename,
                "saved_path": relative_path
            }

        except Exception as e:
            logger.error(f"文件保存失败: {str(e)}", exc_info=True)
            raise HTTPException(status_code=500, detail=f"文件保存失败: {str(e)}")